package com.bootdo.cash.controller;

import com.bootdo.common.annotation.IpFilter;
import com.bootdo.common.annotation.Log;
import com.bootdo.common.config.Constant;
import com.bootdo.common.redis.lock.CommonRedisLock;
import com.bootdo.common.utils.*;
import com.bootdo.cash.domain.CashDO;
import com.bootdo.cash.service.CashService;
import com.bootdo.essential.domain.BankDO;
import com.bootdo.essential.serivce.BankService;
import com.bootdo.order.domain.RechargeDO;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;

import static com.bootdo.common.utils.ShiroUtils.getUserId;

/**
 * @Desc 商户提现
 * @date 2019/12/13
 *
 */
@Controller
@RequestMapping("/cash/cash")
public class CashController {

    @Autowired
    private CashService cashService;
    @Autowired
    private BankService bankService;

    @Autowired
    protected StringRedisTemplate stringRedisTemplate;

    private final String PREFIX = "cash/cash";

    @GetMapping()
    @RequiresPermissions("cash:cash:cash")
    String cash(Model model) {
        return PREFIX + "/list";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("cash:cash:cash")
    PageUtils list(@RequestParam Map<String, Object> params){
        //查询列表数据
        Query query = new Query(params);
        List<CashDO> list = cashService.list(query);
        int total = cashService.count(query);
        PageUtils pageUtils = new PageUtils(list, total);
        return pageUtils;
    }

    @RequiresPermissions("cash:cash:cash")
    @Log("获取发起人备注")
    @PostMapping("/findUser")
    @ResponseBody
    R findUser(Long userId) {
        String name = cashService.findUser(userId);
        return R.ok(name);
    }

    @RequiresPermissions("cash:cash:add")
    @Log("添加提现信息")
    @GetMapping("/add")
    String add(Model model) {
        //获取当前商户可提现金额
        Double money = cashService.findMerchantMoney(getUserId());
        BankDO bank = bankService.getByUser(getUserId());
        model.addAttribute("countMoney", money);
        model.addAttribute("userId", getUserId());
        model.addAttribute("bank", bank);
        model.addAttribute("type", "2");
        return PREFIX + "/add";
    }

    @RequiresPermissions("cash:cash:add")
    @Log("保存提现信息")
    @PostMapping("/save")
    @ResponseBody
    @IpFilter
    R save(CashDO cash) {
        int count = cashService.save(cash);
        if (count > 0) {
            return R.ok();
        } else if (count == -2){
            return R.error("可提现金额不足");
        } else {
            return R.error();
        }
    }

    @RequiresPermissions("cash:cash:edit")
    @Log("编辑提现状态")
    @GetMapping("/edit/{id}")
    String edit(Model model, @PathVariable("id") Long id) {
        CashDO cash = cashService.get(id);
        model.addAttribute("user", cash);
        return PREFIX + "/edit";
    }

    @RequiresPermissions("cash:cash:edit")
    @Log("修改提现状态")
    @PostMapping("/update")
    @ResponseBody
    R update(CashDO cash) {
        if (cashService.update(cash) > 0) {
            return R.ok();
        }
        return R.error();
    }

    @RequiresPermissions("cash:cash:receiv")
    @Log("添加发起收款信息")
    @GetMapping("/receiv")
    String receiv(Model model){
        //获取平台可提现金额
        Double money = cashService.findPlatformMoney();
        BankDO bank = bankService.getByUser(getUserId());
        model.addAttribute("countMoney", money);
        model.addAttribute("userId", getUserId());
        model.addAttribute("bank", bank);
        model.addAttribute("type", "1");
        return PREFIX + "/add";
    }

    @RequiresPermissions("cash:cash:receiv")
    @Log("保存发起收款信息")
    @PostMapping("/receiv/save")
    @ResponseBody
    @IpFilter
    R receivSave(CashDO cash) {
        int count = cashService.save(cash);
        if (count > 0) {
            return R.ok();
        } else if (count == -2){
            return R.error("可收款金额不足");
        } else {
            return R.error();
        }
    }

    @Log("支付校验")
    @PostMapping("/recharge/check")
    @ResponseBody
    R rechargeCheck(@RequestParam Long id){
        CommonRedisLock commonLock = new CommonRedisLock(stringRedisTemplate, Constant.RECHARGE_CHECK + id);
        try {
            if (commonLock.tryLock(3)) {
                CashDO cash = cashService.get(id);
                if (0 == cash.getStatus().intValue()){
                    cash.setStatus(1);
                    if (cashService.update(cash) > 0) {
                        return R.ok();
                    }
                }
            }
        } catch (Exception e){
            return R.error();
        } finally {
            commonLock.unlock();
        }
        return R.error();
    }

    @RequiresPermissions("cash:cash:recharge")
    @Log("支付")
    @GetMapping("/recharge/{id}")
    String recharge(Model model, @PathVariable("id") Long id){
        CashDO cash = cashService.get(id);
        model.addAttribute("userId", id);
        model.addAttribute("user", cash);
        long cashMoney = Math.round(cash.getCashMoney() * 100);
        long lockingMoney = Math.round(cash.getLockingMoney() * 100);
        long actualMoney = Math.round(cash.getActualArrival() * 100);
        DecimalFormat df = new DecimalFormat("0.00");
        model.addAttribute("maxMoney",  Double.valueOf(df.format((float)(cashMoney - lockingMoney - actualMoney)/100)));
        return PREFIX + "/recharge";
    }


    @ResponseBody
    @PostMapping("/upload/{id}")
    @IpFilter
    R upload(@RequestParam("file") MultipartFile file) {
        try {
            String fileName = file.getOriginalFilename();
            String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
            RechargeDO recharge = cashService.upload(file.getBytes(), fileType);
            return R.ok(recharge);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    @Log("修改支付信息")
    @PostMapping("/recharge/update")
    @ResponseBody
    R rechargeUpdate(@RequestParam Long id) {
        CashDO cash = cashService.get(id);
        cash.setStatus(0);
        if (cashService.update(cash) > 0) {
            return R.ok();
        }
        return R.error();
    }

    @Log("保存支付信息")
    @PostMapping("/rechargeSave")
    @ResponseBody
    @IpFilter
    R rechargeSave(RechargeDO recharge) {
        int count = cashService.rechargeSave(recharge);
        if (count > 0) {
            return R.ok();
        } else if (count == -2) {
            return R.error("当前可充值金额不足");
        } else if (count ==-3){
            return R.error("当前充值已被锁定");
        } else if (count == -5) {
            return R.error("付款金额不能为空");
        } else if (count == -6) {
            return R.error("付款金额不能为0");
        }
        return R.error();
    }

    @GetMapping("/cashExamine")
    @RequiresPermissions("cash:cash:cashExamine")
    String cashExamine(Model model) {
        return PREFIX + "/cashExamine";
    }

    @ResponseBody
    @GetMapping("/examineList")
    @RequiresPermissions("cash:cash:cashExamine")
    PageUtils examineList(@RequestParam Map<String, Object> params){
        //查询列表数据
        Query query = new Query(params);
        List<CashDO> list = cashService.list(query);
        int total = cashService.count(query);
        PageUtils pageUtils = new PageUtils(list, total);
        return pageUtils;
    }

    @GetMapping("/editExamine/{id}")
    @RequiresPermissions("cash:cash:editExamine")
    String editExamine(Model model, @PathVariable("id") Long id) {
        model.addAttribute("id", id);
        return PREFIX + "/editExamine";
    }

    @IpFilter
    @ResponseBody
    @Log("审核提现申请")
    @PostMapping("/updateExamine")
    @RequiresPermissions("cash:cash:editExamine")
    R updateExamine(CashDO cash) {
        CommonRedisLock commonLock = new CommonRedisLock(stringRedisTemplate, "CASHEXAMINE" + cash.getId());
        try {
            if (commonLock.tryLock(3)) {
                if (cashService.updateExamine(cash) > 0) {
                    return R.ok();
                }
            }
            return R.error();
        } finally {
            commonLock.unlock();
        }
    }

}
